package vn.hanelsoft.openwifi.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.common.MyThread;
import vn.hanelsoft.openwifi.common.UtilsCommon;
import vn.hanelsoft.openwifi.common.network_service.utils.NetworkUtil;
import vn.hanelsoft.openwifi.model.delegate.ServerDelegate;
import vn.hanelsoft.openwifi.model.entity.EntityWifi;
import vn.hanelsoft.openwifi.model.object.ObjectWifi;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


public class MapWifiActivity extends FragmentActivity implements
		OnClickListener {

	Context mContext;

	Button btnMyLocation;
	GoogleMap googleMap;
	Location currentLocation;
	Handler _getMyLocationHandler;
	MyThread _myThread;
	LocationManager myLocationManager;
	CameraPosition cameraPosition;
	Marker marker;
	ObjectWifi mObjectWifi;
	ArrayList<ObjectWifi> listWifiOnServer;
	boolean checkDisconnectWifi = true;
	ProgressBar progressBarLoading;
	
	
	EntityWifi entityWifi = new EntityWifi(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_map);
		initDB();
		initView();
		if (NetworkUtil.checkNetWork(getApplicationContext())) {
			getMyLocation();
			initMap();
		} else {
			Toast.makeText(mContext,
					mContext.getString(R.string.not_connect_internet),
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnMyLocation:
			if (NetworkUtil.checkNetWork(getApplicationContext())) {
				if (_myThread != null) {
					_myThread.myresume();
				} else {
					_myThread = new MyThread("", _getMyLocationHandler);
				}
			} else {
				Toast.makeText(mContext,
						mContext.getString(R.string.not_connect_internet),
						Toast.LENGTH_LONG).show();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		activityFinish();
	}

	@Override
	protected void onUserLeaveHint() {
		if (checkDisconnectWifi == false) {
			checkDisconnectWifi = true;
		} else {
			UtilsCommon.disConnectWifi(mContext);
		}
		super.onUserLeaveHint();
	}

	/*------------------- Custom Function ------------------------*/

	void initDB() {
		mContext = this;
		myLocationManager = (LocationManager) mContext
				.getSystemService(Context.LOCATION_SERVICE);
		listWifiOnServer = new ArrayList<ObjectWifi>();
		checkDisconnectWifi = true;
	}

	void initView() {
		btnMyLocation = (Button) findViewById(R.id.btnMyLocation);
		btnMyLocation.setOnClickListener(this);
		
		progressBarLoading = (ProgressBar)findViewById(R.id.progressBarLoading);

		googleMap = ((SupportMapFragment) getSupportFragmentManager()
				.findFragmentById(R.id.map)).getMap();
		try {
			googleMap.setMyLocationEnabled(true);
			googleMap.getUiSettings().setMyLocationButtonEnabled(false);
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {

				@Override
				public void onMapLongClick(LatLng location) {
					if (NetworkUtil.checkNetWork(getApplicationContext())) {
						progressBarLoading.setVisibility(View.VISIBLE);
						String lat = String.valueOf(location.latitude);
						String lon = String.valueOf(location.longitude);
						ServerDelegate.getWifi(mhandlerGetWifiFromServer, lat, lon);
					} else {
						Toast.makeText(MapWifiActivity.this, "Not connect Internet", Toast.LENGTH_SHORT).show();
					}
					
				}
			});
			googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
				@Override
				public void onInfoWindowClick(Marker marker) {
					for(int i=0; i< listWifiOnServer.size(); i++)
					{
						mObjectWifi = listWifiOnServer.get(i);
						if(mObjectWifi.getWifiSSID().equals(marker.getTitle()))
						{
							if(entityWifi.checkWifi(mObjectWifi.getWifiBSSID())){
								if (entityWifi.update(mObjectWifi)) {
									Toast.makeText(MapWifiActivity.this, "Update Successfully", Toast.LENGTH_SHORT).show();
								}else{
									Toast.makeText(MapWifiActivity.this, "Update Failed", Toast.LENGTH_SHORT).show();
								}
							}
							else{
								if (entityWifi.add(mObjectWifi) > 0) {
									Toast.makeText(MapWifiActivity.this, "Insert Successfully", Toast.LENGTH_SHORT).show();
								}else{
									Toast.makeText(MapWifiActivity.this, "Insert Failed", Toast.LENGTH_SHORT).show();
								}
							}
						}
					}
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void activityFinish() {
		finish();
		overridePendingTransition(
				R.drawable.activity_transaction_trans_right_in,
				R.drawable.activity_transaction_trans_right_out);
	}

	public void initMap() {
		if (NetworkUtil.checkNetWork(getApplicationContext())) {
			if (_myThread != null) {
				_myThread.myresume();
			} else {
				_myThread = new MyThread("", _getMyLocationHandler);
			}
		} else {
			Toast.makeText(mContext,
					mContext.getString(R.string.not_connect_internet),
					Toast.LENGTH_LONG).show();
		}
	}

	@SuppressLint("HandlerLeak")
	public void getMyLocation() {
		// custom dialog
		final Dialog dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_loading);
		_getMyLocationHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				try {
					if (googleMap.getMyLocation() != null) {
						dialog.dismiss();
						_myThread.mysuspend();
						currentLocation = googleMap.getMyLocation();
						final double myLat = currentLocation.getLatitude();
						final double myLon = currentLocation.getLongitude();
						cameraPosition = new CameraPosition(new LatLng(myLat,
								myLon), 16, 30, 45);
						googleMap.animateCamera(CameraUpdateFactory
								.newCameraPosition(cameraPosition));
//						drawMap();
					} else {
						dialog.show();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		};
	}

//	void drawMap() {
//		if (currentLocation != null) {
//			
//		} else {
//			boolean isGetLocation = false;
//			while (isGetLocation == false) {
//				if (currentLocation != null) {
//					isGetLocation = true;
//				} else {
//					try {
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//			}
//		}
//		ServerDelegate.getWifi(mhandlerGetWifiFromServer, "", "");
//	}

	public void canvasMarker(LatLng mLatLng, ObjectWifi wifiJSONObject) {
		marker = googleMap.addMarker(new MarkerOptions().position(mLatLng).icon(
				BitmapDescriptorFactory.fromResource(R.drawable.marker_wifi)).title(wifiJSONObject.getWifiSSID()).snippet(getString(R.string.press_to_save_wifi)));

		marker.showInfoWindow();
	}

	Handler mhandlerGetWifiFromServer = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					JSONArray data = new JSONArray();
					data = dataJSONObject.getJSONArray("data");
					if (data != null && data.length() > 0) {
						JSONObject wifiJSONObject = null;
						for (int i = 0; i < data.length(); i++) {
							wifiJSONObject = new JSONObject();
							wifiJSONObject = data.getJSONObject(i);
							
							String strLat = wifiJSONObject
									.getString("lattitue");
							String strLng = wifiJSONObject
									.getString("longitue");
							
							mObjectWifi = new ObjectWifi();
							mObjectWifi.setWifiBSSID(wifiJSONObject
									.getString("BSSID"));
							mObjectWifi.setWifiSSID(wifiJSONObject
									.getString("SSID"));
							mObjectWifi.setWifiPassword(wifiJSONObject
									.getString("passkey"));
							mObjectWifi.setLat(wifiJSONObject
									.getString("lattitue"));
							mObjectWifi.setLng(wifiJSONObject
									.getString("longitue"));
							listWifiOnServer.add(mObjectWifi);

							if (strLat != null && strLng != null) {
								try {
									LatLng mLatLng = new LatLng(
											Double.parseDouble(strLat),
											Double.parseDouble(strLng));
									canvasMarker(mLatLng, mObjectWifi);
								} catch (Exception e) {
									// TODO: handle exception
								}
							}
						}
						wifiJSONObject = null;
					} else {
						Toast.makeText(mContext, getString(R.string.don_t_have_any_open_wifi_at_here), Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
				}
			} else {
			}
			progressBarLoading.setVisibility(View.GONE);
		}
	};

}
